var validator;
var cd = new Date();
var minYear = cd.getFullYear() - 120;
var minMon = cd.getMonth();
var minDay = cd.getDate();
var maxYear = cd.getFullYear()-1;
var maxMon = minMon;
var maxDay = minDay;
var bdayErrMsg = 'Please input reasonable age, at least between 1~120 years old.';

$(document).ready(function(){	
	/* 
	TODO: press enter to submit form
	$('#username_id').keyup(function (e){
		if( e.keyCode == 13 ) {
			$('#eventSignupForm_submit').click();
		}
	});
	$('#password_id').keyup(function (e){
		if( e.keyCode == 13 ) {
			$('#eventSignupForm_submit').click();
		}
	});
	*/
	$.validator.addMethod("date", function(date, element) {
                return this.optional(element) || date.match(/^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$/);
            }, "Please specify a valid date : YYYY-MM-DD");
	
	$.validator.addMethod('mindate',function(v,el,minDate){
				if (this.optional(el)){
					return true;
				}
				var curDate = new Date($(el).val());
				return curDate >= minDate;
			}, bdayErrMsg);
	$.validator.addMethod('maxdate',function(v,el,maxDate){
				if (this.optional(el)){
					return true;
				}
				var curDate = new Date($(el).val());
				return curDate <= maxDate;
			}, bdayErrMsg);
			
	validator = $('#eventSignupForm').validate({
			rules: {
			  name: {
				required: true,
			  },
			  bday: {
				mindate: new Date(minYear,minMon,minDay),
				maxdate: new Date(maxYear,maxMon,maxDay),
				required: true,
				date: true,
			  },
			  pid: {
				required: true,
			  },
			  phoneNum: {
				required: true,
			  },
			  email:{
				required: true,
				email: true,
			  },
			  emgcyContact:{
				required: true,
			  },
			  emgcyContPhone:{
				required: true,
			  },
			  recaptcha_response_field: {
				required: true,
			  },
			},
			
			highlight: function(element) {
				var attr = $(element).attr("style")
				if( typeof attr != 'undefined' && attr != false ) {
					$(element).css({'border-color':'#b94a48'});
				}
				else {
					$(element).closest('.form-group').addClass('has-error');
				}
			},
			unhighlight: function(element, errorClass, validClass) {
				var attr = $(element).attr("style")
				if( typeof attr != 'undefined' && attr != false ) {
					$(element).css({'border-color':''});
				}
				else {
					$(element).closest('.form-group').removeClass('has-error');
				}
			},
			
			submitHandler: function(form) {
				form.submit();
			},
			
			errorPlacement: function (error, element){
				error.addClass('text-muted');
				element.after(error);
			},
		});
		
	ajax_init();
	
	$('#eventSignupForm_submit').click(function(e){
		// TODO : create validate rules
		if( $("#eventSignupForm").valid() == false ){
			validator.focusInvalid();
			return;
		}
		$('.signup_form_errormsg').hide();
		$('.signup_form_errormsg_captcha').hide();
		$('#recaptcha_response_field').css({'border-color':'', 'border-width':'1px'});
		
		// auth state : waiting
		ajax_waiting();
		
		data = $('#eventSignupForm').serialize();
		Dajaxice.events.eventSignupJSON(resultCallback, {'form':data}, {'error_callback': ajax_error});
		
		e.preventDefault();
		return false;
	});
	
	// selection fields
	$('#gender_select').change( function (e) {
		$('#gender_id').val(e.target.value);
		$(this).children('option[value='+$(this).val()+']').attr('selected','selected');
		$(this).children('option[value!='+$(this).val()+']').removeAttr('selected');
	});
	
	$('.country-selector').change( function (e) {
		$('#country_id').val(e.target.value);
		$(this).children('option[value='+$(this).val()+']').attr('selected','selected');
		$(this).children('option[value!='+$(this).val()+']').removeAttr('selected');
	});
	
	$('#estimateTime_select').change( function (e) {
		$('#estimateTime_id').val(e.target.value);
		$(this).children('option[value='+$(this).val()+']').attr('selected','selected');
		$(this).children('option[value!='+$(this).val()+']').removeAttr('selected');
	});
	
	$('#importFromProfile').click(function(e) {
		Dajaxice.events.importFromUserProfileJSON(importResult, {'error_callback': importError});
	});
});

function importResult(data) {
	console.log("dajax callback " + data.result);
	
	if( data.name != null ) $('#name_id').val(data.name);
	if( data.bday != null ) $('#bday_id').val(data.bday);
	if( data.pid != null ) $('#pid_id').val(data.pid);
	if( data.phoneNum != null ) $('#phoneNum_id').val(data.phoneNum);
	if( data.email != null ) $('#email_id').val(data.email);
	if( data.emgcyContact != null ) $('#emgcyContact_id').val(data.emgcyContact);
	if( data.emgcyContPhone != null ) $('#emgcyContPhone_id').val(data.emgcyContPhone);
	
	if( data.gender != null )
	{
		$('#gender_id').val(data.gender);
		$('#gender_id').siblings().val(data.gender);
	}
	if( data.nationality != null )
	{
		$('#nationality_id').val(data.nationality);
		$('#nationality_id').siblings().val(data.gender);
	}
}
function importError(data) {
	console.log("dajax callback " + data.result);
}

function resultCallback(data) {
		console.log("dajax callback " + data.result);
		 
		// auth state : finish
		ajax_finish();
		
		// 3. success signup
		if( data.result == "succeed" )
		{
			window.location = data.redirect_to;
			return;
		}
		
		// refresh captcha if any error occurs
		$('#recaptcha_reload_btn')[0].click();
		
		// 0.5. captcha failed
		if( data.result == "captch_failed")
		{
			$('.signup_form_errormsg_captcha').show();
			$('#recaptcha_response_field').css({'border-color':'#b94a48', 'border-width':'2px'});
			$('#recaptcha_response_field').focus();
		}
		// 1. event_id_not_exist
		else if( data.result == "event_id_not_exist")
		{
			$('.signup_form_errormsg_eventid').show();
		}
		// 2. participant_is_existed
		else if( data.result == "participant_is_existed")
		{
			$('.signup_form_errormsg').show();
		}
		// 2.5 invalid_bday
		else if( data.result == "invalid_bday")
		{
			var $validator = $("#eventSignupForm").validate();
			errors = { bday: bdayErrMsg };
			$validator.showErrors(errors);
		}
		
}

function ajax_error() {ajax_finish();}
function ajax_init() {
	$('.signup_form_errormsg_eventid').hide();
	$('.signup_form_errormsg').hide();
	$('.signup_form_errormsg_captcha').hide();
	
	$('#recaptcha_response_field').removeClass('has-error');
	
	$('.form-footer .controls').show();
	$('.form-footer .progress').hide();
}
function ajax_waiting() {
	$('.form-footer .controls').hide();
	$('.form-footer .progress').show();
}
function ajax_finish() {ajax_init();}